Skip to content

Conversation

ScriptedAlchemy
Copy link
Member

@ScriptedAlchemy ScriptedAlchemy commented Oct 4, 2025

This pull request enhances support for Web Worker and other dynamic entrypoints in the module federation runtime, ensuring that async entry runtime helpers are available when cloning runtimes. It introduces new logic in the runtime plugin to correctly handle dedicated runtimes for async entrypoints, adds thorough testing for these scenarios, and demonstrates the feature with a new worker-based integration test and demo. The changes also include improvements to the runtime module code generation and relevant updates to demo and test files.

Enhancements to async entrypoint and Web Worker runtime support:

  • Added logic in FederationRuntimePlugin to ensure that async entrypoints (such as Web Workers) receive dedicated runtime chunks, cloning necessary runtime modules and requirements from shared runtime chunks. This prevents missing runtime helpers in dynamically loaded contexts. [1] [2] [3]
  • Updated RemoteRuntimeModule to initialize federation globals and options more robustly, and to conditionally invoke remote runtime helpers only if available, improving safety and compatibility for dynamic runtimes. [1] [2]

Testing and verification:

  • Added comprehensive unit and integration tests to verify that runtime helpers are present on both shared and worker chunks, and that async entrypoints receive correct runtime modules. [1] [2] [3]

Demo and Cypress integration:

  • Expanded the runtime demo app to include a Web Worker test case, with a new WorkerDemo React component and corresponding Cypress test to verify correct worker behavior in the browser. [1] [2] [3] [4] [5] [6]

Configuration and documentation:

  • Added a .changeset entry describing the patch and updated the demo app's webpack configuration to ensure compatibility with the new runtime logic. [1] [2]

These changes collectively improve the reliability and flexibility of module federation in environments with dynamic entrypoints such as Web Workers.

fixes #4085

- reassign non-initial entrypoints to their own runtime when runtimeChunk is single or object form
- add worker demo and cypress assertion covering the web worker bootstrap
Copy link

changeset-bot bot commented Oct 4, 2025

🦋 Changeset detected

Latest commit: cb7434b

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 36 packages
Name Type
@module-federation/enhanced Patch
@module-federation/modern-js Patch
@module-federation/nextjs-mf Patch
@module-federation/node Patch
@module-federation/rsbuild-plugin Patch
@module-federation/rspress-plugin Patch
@module-federation/storybook-addon Patch
@module-federation/modernjsapp Patch
remote5 Patch
website-new Patch
@module-federation/runtime Patch
@module-federation/rspack Patch
@module-federation/webpack-bundler-runtime Patch
@module-federation/sdk Patch
@module-federation/runtime-tools Patch
@module-federation/managers Patch
@module-federation/manifest Patch
@module-federation/dts-plugin Patch
@module-federation/third-party-dts-extractor Patch
@module-federation/devtools Patch
@module-federation/bridge-react Patch
@module-federation/bridge-vue3 Patch
@module-federation/bridge-shared Patch
@module-federation/bridge-react-webpack-plugin Patch
@module-federation/retry-plugin Patch
@module-federation/data-prefetch Patch
@module-federation/error-codes Patch
@module-federation/inject-external-runtime-core-plugin Patch
@module-federation/runtime-core Patch
create-module-federation Patch
@module-federation/cli Patch
@module-federation/metro Patch
@module-federation/metro-plugin-rnef Patch
@module-federation/metro-plugin-rnc-cli Patch
@module-federation/esbuild Patch
@module-federation/utilities Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link

netlify bot commented Oct 4, 2025

Deploy Preview for module-federation-docs ready!

Name Link
🔨 Latest commit cb7434b
🔍 Latest deploy log https://app.netlify.com/projects/module-federation-docs/deploys/68ef50c09fdfff0008fbe289
😎 Deploy Preview https://deploy-preview-4116--module-federation-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@ScriptedAlchemy
Copy link
Member Author

@codex harshly review the changes here. not completly happy with the solutions applied here. do lots of research and give review comments

Copy link

Summary

  • Added REVIEW.md capturing three blocking concerns: the async runtime detection still ignores manually shared runtimes, runtime naming becomes non-deterministic for anonymous workers, and the remote loader now silently no-ops without the bundler runtime. REVIEW.mdL5-L12
  • Noted the remaining duplication TODO in the worker runtime test suite so it doesn’t get locked in as the expected behaviour. REVIEW.mdL14-L16

Testing

  • ⚠️ not run (review-only change)

View task →

@ScriptedAlchemy
Copy link
Member Author

@codex harshly review pr

Copy link

Summary

  • Added REVIEW.md outlining three blocking regressions introduced by the worker runtime changes (manual shared runtimes still break, anonymous runtime naming is non-deterministic, and remote loading now silently no-ops without the bundler runtime) plus a reminder to address the duplicated worker test fixture. REVIEW.mdL1-L17

Testing

  • ⚠️ not run (documentation-only change)

View task →

@ogonkov
Copy link
Contributor

ogonkov commented Oct 6, 2025

@ScriptedAlchemy this will fix any references to modules via new URL(..., import.meta.url) syntax?

I'm asked because we use custom Worker constructor :/

@ScriptedAlchemy
Copy link
Member Author

Any chance you can send a PR or branch and modify one of our apps in /apps to replicate your needs so I can run against that app within this monorepo

ScriptedAlchemy and others added 8 commits October 6, 2025 15:52
- Add comprehensive test for webpack worker compilation with Module Federation
- Test verifies worker syntax new Worker(new URL()) compiles correctly
- Validates federated modules (React, ComponentA) are accessible in worker context
- Tests both CommonJS (async-node) and ESM (node14) module outputs
- Provides URL to test scope via moduleScope for Node.js targets
- All 10 tests pass successfully (5 tests × 2 builds)
Added beforeEach hook to reset React version to '0.1.2' before running worker tests.
This prevents test contamination from other container tests (like 1-container-full)
that set React version to '3.2.1' and cause the worker test to fail with unexpected
version mismatches.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
… cross-context relocation

Enhanced runtime chunk detection and federation runtime injection to properly support worker
threads. Added safeguards to prevent runtime module relocation between different execution
contexts (main thread vs workers).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…ker demo

- Enable runtimeChunk in webpack config to ensure bundler runtime is available
- Update WorkerDemo to use WorkerWrapper instead of module worker
- This fixes the 'bundler runtime is required to load remote chunk' error in workers
const value = event.data && event.data.value;
const federation =
typeof __webpack_require__ !== 'undefined'
? __webpack_require__.federation || {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is some debug code? Because in my project i got this problem, when federation is undefined (i was unable to reproduce it, but found another error, that i was reported in issue)

ScriptedAlchemy and others added 18 commits October 11, 2025 22:44
…ndencies in workers

Changed EmbedFederationRuntimeModule to use stage 40 (higher than STAGE_TRIGGER=20)
to ensure it wraps __webpack_require__.x AFTER StartupChunkDependenciesRuntimeModule.

This fixes the issue where workers failed with "Cannot read properties of undefined
(reading 'remotes')" because the federation runtime wasn't initialized before the
remotes handler was invoked.

The execution order is now:
1. StartupChunkDependencies wraps __webpack_require__.x (stage 20)
2. EmbedFederation wraps it again (stage 40)
3. When called: EmbedFederation → init runtime → StartupChunkDependencies → load chunks

Also added logging to track execution flow and suppressed async/await warnings
in webpack config.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…tion fix

Added and updated tests to verify the stage 40 fix for EmbedFederationRuntimeModule:

- Updated FederationRuntimePluginWorkerRuntime.test.ts to verify runtime module
  execution order in worker bundles (EmbedFederation appears AFTER StartupChunkDependencies)
- Updated FederationRuntimePluginHostRuntime.test.ts to add test for main bundle
  generation with correct runtime module order
- Created HoistContainerReferencesPlugin.test.ts with 13 comprehensive tests covering:
  - Plugin application and hook registration
  - Runtime chunk detection
  - Module hoisting for container entries, federation runtime, and worker runtime
  - Chunk cleanup
  - getAllReferencedModules helper function with various traversal types
- Updated RemoteRuntimeModule.test.ts to include defensive initialization lines

All 632 tests passing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…rder

Refactored both FederationRuntimePlugin compiler-unit tests to use
programmatic webpack execution instead of spawning webpack-cli:

- FederationRuntimePluginHostRuntime.test.ts:
  - Removed swc-loader dependency by using plain JavaScript
  - Changed to use programmatic webpack API (runWebpack helper)
  - Adjusted first test to expect successful build (not error)
  - Changed second test to use development mode to preserve markers
  - Updated assertions to check for actual functional code

- FederationRuntimePluginWorkerRuntime.test.ts:
  - Fixed ROOT path calculation (was off by one level)

All tests now pass successfully.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Fixed FederationRuntimePluginWorkerRuntime.test.ts by:
- Removed `plugin._options.remotes = {}` which was causing module resolution errors
- Fixed collectInfrastructureErrors to handle non-iterable entries properly
- Simplified error checking to log errors for debugging

The test was failing because it removed all remotes, but the source code
imports from remote1 modules (WebpackSvg, WebpackPng, useCustomRemoteHook).
The build now succeeds by keeping the remotes configuration intact.

All 73 container tests now pass.
Fixed Next.js e2e tests failing with "__webpack_require__.f is undefined" by
changing the execution order in EmbedFederationRuntimeModule:

**Before:**
1. Require federation entry
2. Call prevStartup()

**After:**
1. Call prevStartup() - initializes webpack runtime handlers
2. Require federation entry - handlers are now available

The federation entry imports modules that depend on webpack runtime handlers
like __webpack_require__.f.consumes. By calling prevStartup first, we ensure
all these handlers are registered before the federation entry is required.

This fixes the error:
"Cannot read properties of undefined (reading 'consumes')"
at __webpack_require__.f.consumes

Also changed stage from 40 to 30 to run earlier in the initialization sequence
while still being after StartupChunkDependenciesRuntimeModule (stage 20).
Changes:
- Simplified EmbedFederationRuntimeModule to load federation entry at STAGE_NORMAL
- Removed stub bundlerRuntime approach (caused merging issues with prevFederation)
- Updated Cypress configs to use CI env variable for retry logic (0 locally, 2-3 in CI)
- Created run-next-e2e.mjs script for local Next.js e2e testing
- Added RUNTIME_INIT_FIX.md documentation explaining the stage ordering issue
- Deleted unused ChildCompilationRuntimePlugin.ts

Known Issue: Next.js SSR still has 500 errors during page rendering.
The federation entry loads correctly in client bundles but server bundles may need investigation.

🤖 Generated with Claude Code
https://claude.com/claude-code

Co-Authored-By: Claude <[email protected]>
…tialization

Fixes worker runtime initialization while maintaining Next.js compatibility by
detecting chunk loading type and applying appropriate runtime module stages.

- JSONP chunks (Next.js): STAGE_ATTACH (10) - loads inside startup hook
- Worker chunks (import-scripts): STAGE_BASIC (5) - loads immediately before RemoteRuntimeModule
- Follows webpack's pattern from JsonpChunkLoadingPlugin for chunk type detection
- Adds comprehensive unit tests for stage selection logic

Resolves initialization timing issues where bundlerRuntime was undefined when
RemoteRuntimeModule tried to access it in worker environments.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
… pattern

Updates FederationRuntimePluginWorkerRuntime test to reflect the new
implementation where worker chunks use immediate execution (stage 5)
instead of startup hook wrapper pattern.

- Removes checks for old startup hook pattern (prevStartup wrapper)
- Verifies federation runtime module is present
- Validates federation entry is loaded regardless of execution pattern

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Build with WebWorkers seems broken

2 participants